<template>
  <div class="view-container">
    <header-module :left-custom="true" :padding="true">
      <template #left-con>
        <span v-if="boole">变更代理</span>
        <span v-else>新建代理</span>
      </template>
      <template #btn>
        <el-button class="border-btn" size="small" @click="handlBack">返回</el-button>
        <el-button size="small" type="primary" @click="handlSubmit">保存</el-button>
      </template>
    </header-module>

    <div class="main-content">
      <el-form ref="openRef" :model="openForm" :rules="rules" label-width="140px" size="small">
        <el-row gutter="40">
          <el-col :span="24">
            <item-title title="基本信息" />
          </el-col>

          <el-col :span="24">
            <el-form-item label="代理商类型" prop="agentType">
              <el-radio-group v-model="openForm.agentType" disabled @change="handlRadio">
                <el-radio label="agent">企业代理</el-radio>
                <el-radio label="agent_person">兼职大包</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item v-if="openForm.agentType === 'agent'" label="代理商名称" prop="agentName">
              <el-input v-model="openForm.agentName" clearable placeholder="请输入代理商名称" />
            </el-form-item>
            <el-form-item v-if="openForm.agentType === 'agent_person'" label="兼职姓名" prop="userName">
              <el-input v-model="openForm.userName" clearable placeholder="请输入兼职人员姓名" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent'" :span="8">
            <el-form-item label="所在地区" prop="value">
              <el-cascader v-model="openForm.value" :popper-append-to-body="false" style="width:100%"
                placeholder="请选择地区" :options="cityList"
                :props="{ value:'regionCode',label:'regionName',expandTrigger: 'hover' }" @change="handlCity" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent_person'" :span="8">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="openForm.sex">
                <el-radio label="1">男</el-radio>
                <el-radio label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent'" :span="8">
            <el-form-item label="详细地址" prop="address" :required="openForm.agentType === 'agent'">
              <el-input v-model="openForm.address" clearable placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent'" :span="8">
            <el-form-item label="联系人" prop="userName">
              <el-input v-model="openForm.userName" clearable placeholder="请输入联系人" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="openForm.tel" clearable placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent'" :span="8">
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input v-model="openForm.creditCode" clearable placeholder="请输入统一社会信用代码" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent_person'" :span="8">
            <el-form-item label="联系地址" prop="address" :required="openForm.agentType === 'agent'">
              <el-input v-model="openForm.address" clearable placeholder="请输入联系地址" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent_person'" :span="8">
            <el-form-item label="身份证" prop="cardNumber">
              <el-input v-model="openForm.cardNumber" clearable placeholder="请输入身份证号码" />
            </el-form-item>
          </el-col>

          <el-col v-if="openForm.agentType === 'agent_person'" :span="24">
            <el-form-item label="身份证附件" prop="cardFiles">
              <div class="qualityFiles-container">
                <div v-for="(item,index) in openForm.cardFiles" :key="index" class="file-item">
                  <image-upload-view ref="imageUploadView"  :data="item" />
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <item-title title="意向代理业务" prompt="（非必填，有意向代理业务时可维护录入）">
              <template #btn>
                <el-button class="border-btn" size="mini" @click="handlAdd(null)">添加</el-button>
                <el-button class="border-btn" size="mini" @click="handlDelete(null,1)">全部删除</el-button>
              </template>
            </item-title>
          </el-col>
          <el-col :span="24">
            <table-view :data="openForm.list" header-cell-class-name="table-header" size="medium" border>

              <el-table-column prop="productName" label="代理产品" header-align="center" :show-overflow-tooltip="true" />

              <el-table-column prop="productLineName" label="产品线" align="center" :show-overflow-tooltip="true" />

              <el-table-column label="代理地区" header-align="center" :show-overflow-tooltip="true">
                <template #default="{row}">
                  <area-list-view :areas="row.region" />
                </template>
              </el-table-column>

              <el-table-column label="代理属性" align="center" :show-overflow-tooltip="true">
                <template #default="{row}">
                  <span v-for="(item,index) in row.agentIntentionAttribute" :key="index">
                    {{ getLabel('agentAttribute', item) }}

                  </span>
                </template>
              </el-table-column>

              <el-table-column prop="terminalName" label="代理终端" align="center" :show-overflow-tooltip="true">
                <template #default="{row}">
                  <el-tooltip class="item" effect="dark" :content="handleTerminalName(row.terminalList)"
                    placement="top-start">
                    <span> {{row.terminalName}}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button type="text" @click="handlAdd(scope)">编辑</el-button>
                  <el-button type="text" @click="handlDelete(scope.$index,2)">删除</el-button>
                </template>
              </el-table-column>
            </table-view>
          </el-col>
        </el-row>
      </el-form>

    </div>
    <!--添加意向代理-->
    <addAgent ref="refAddAgent" @succsess="succsess" />
  </div>
</template>

<script>
import {
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRefs,
} from "vue";
import area from "@/utils/area";
import { validateVETel } from "@/utils/validate";
import { useRoute, useRouter } from "vue-router";
import { crmStore } from "@CRM/store";

export default {
  name: "Create",
  components: {
    addAgent: defineAsyncComponent(() => import("./addAgent.vue")),
  },
  setup(props, context) {
    //* ************自定义效验**********
    const validateTel = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机码"));
      } else {
        if (validateVETel(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      }
    };
    const validateName = async (rule, value, callback) => {
      if (value === "") {
        callback("请输入代理商名称");
      } else {
        const aaa = await validateVEName(value);
        if (aaa) {
          callback(new Error("代理商名称已存在"));
        } else {
          callback();
        }
      }
    };

    const validateAddress = (rule, value, callback) => {
      if (data.openForm.agentType === "agent") {
        if (value === "") {
          callback(new Error("请输入详细地址"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };

    //* ********************************
    const api = inject("api");
    const currentInstance = getCurrentInstance();
    const router = useRouter();
    const route = useRoute();
    const data = reactive({
      openBoole: false,
      cityList: area,
      openForm: {
        value: null,
        agentNumber: "",
        agentName: "", // 代理商名称
        provinceCode: "", // 省code
        cityCode: "", // 市code
        areaCode: "", // 区code
        address: "", // 详细地址
        userName: "", // 联系人
        tel: "", // 联系电话
        creditCode: "", // 统一信用代征码
        agentType: route.query.type,
        sex: "1",
        cardNumber: "",
        cardFiles:
          JSON.parse(
            JSON.stringify(
              crmStore.getters["jsonData/getJsonData"][
                "part_person_qualification"
              ].data
            )
          ) || [],
        list: [],
      },
      openRef: null,
      rules: {
        agentType: [
          { required: true, message: "请选择代理商类型", trigger: "change" },
        ],
        agentName: [
          { required: true, validator: validateName, trigger: "blur" },
        ],
        address: [{ validator: validateAddress, trigger: "blur" }],
        userName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        tel: [{ required: true, validator: validateTel, trigger: "blur" }],
        value: [{ required: true, message: "请选择地区", trigger: "change" }],
        creditCode: [
          {
            required: true,
            message: "请输入统一社会信用代码",
            trigger: "blur",
          },
        ],
      },
      refAddAgent: null,
      index: -1,
      boole: false,
    });

    const handleTerminalName  =(list)=>{
      var str = ''
      for(let i = 0 ; i < list.length; i++){
        str += list[i].terminalName
        if(i !== list.length - 1){
          str = str + '、'
        }
      }
      return str
    }

    const handlCity = (val) => {
      if (val) {
        data.openForm.provinceCode = val[0];
        data.openForm.cityCode = val[1];
        data.openForm.areaCode = val[2];
        nextTick((_) => {
          data.openRef.clearValidate("provinceCode");
        });
      }
    };

    const validateVEName = async (val) => {
      const paramData = {
        table: "agent",
        column: "agent_name",
        column_data: val,
        id: data.openForm.id ? data.openForm.id : "",
      };
      const booleName = ref(false);
      const res = await api.channelAgent.POTENTIALAGENT_NAME(paramData);
      if (res.code === 0) {
        if (res.data.exist === "1") {
          booleName.value = true;
        } else {
          booleName.value = false;
        }
      } else {
        booleName.value = false;
      }
      return booleName.value;
    };

    const handlRadio = (val) => {
      data.openRef.clearValidate();
      data.openRef.resetFields();
      data.openForm.agentType = val;
    };

    const handlBack = () => {
      router.go(-1);
    };

    const handlAdd = (val) => {
      if (val === null) {
        data.refAddAgent.open(null);
        data.index = -1;
      } else {
        data.index = val.$index;
        data.refAddAgent.open({ ...data.openForm.list[data.index] });
      }
    };

    const handlDelete = (index, num) => {
      if (num === 2) {
        data.openForm.list.splice(index, 1);
      }
      if (num === 1) {
        data.openForm.list = [];
      }
    };

    const succsess = (val) => {
      if (data.index !== -1) {
        data.openForm.list[data.index] = val;
      } else {
        data.openForm.list.push(val);
      }
      console.log(data.openForm.list, "--------");
    };

    const handlDetail = (id) => {
      api.channelAgent.POTENTIALAGENT_DETAIL(id).then((res) => {
        if (res.code === 0) {
          const arr = JSON.parse(JSON.stringify(res.data.data));
          for (let i = 0; i < arr.list.length; i++) {
            const val = arr.list[i];
            if (val.terminalIdList === null) {
              val.terminalIdList = [];
            }
            if (
              typeof val.terminalList === "string" &&
              val.terminalList.constructor === String
            ) {
              val.terminalList = JSON.parse(val.terminalList) || [];
            }
            if (
              typeof val.area === "string" &&
              val.area.constructor === String
            ) {
              val.area = JSON.parse(val.area) || [];
            }
            if (
              typeof val.terminalIdList === "string" &&
              val.terminalIdList.constructor === String
            ) {
              val.terminalIdList = val.terminalIdList || [];
            }
          }
          data.openForm = arr;
          data.openForm.id = arr.id;
          data.openForm.value = [
            data.openForm.provinceCode,
            data.openForm.cityCode,
            data.openForm.areaCode,
          ];
        }
      });
    };

    // 确定
    const handlSubmit = () => {
      console.log(11111);
      data.openRef.validate((valid) => {
        if (valid) {
          console.log("0000000000000000000", data.openForm.id);
          const commit = ref(undefined);
          const msgs = ref("");
          if (route.query.id) {
            commit.value = api.channelAgent.POTENTIALAGENT_CREATE_UPDATE;
            msgs.value = "变更成功";
          } else {
            commit.value = api.channelAgent.POTENTIALAGENT_CREATE_FROM;
            msgs.value = "创建成功";
          }
          if (data.openForm.list.length > 0) {
            data.openForm.list.forEach((item) => {
              item.terminalList = JSON.stringify(item.terminalList);
              item.area = JSON.stringify(item.area);
            });
          }
          if (commit.value) {
            commit.value(data.openForm).then((res) => {
              if (res.code === 0) {
                currentInstance.proxy.customMessage({
                  type: "success",
                  message: msgs.value,
                });
                handlBack();
              } else {
                currentInstance.proxy.customMessage({
                  type: "error",
                  message: res.msg,
                });
              }
            });
          }
        }
      });
    };

    onMounted((_) => {
      if (route.query.id) {
        handlDetail(route.query.id);
        data.boole = true;
      }
    });

    return {
      ...toRefs(data),
      handleTerminalName,
      handlSubmit,
      handlCity,
      validateVEName,
      handlBack,
      handlAdd,
      handlDelete,
      handlRadio,
      succsess,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
